home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 September / Chip_2000-09_cd1.bin / sharewar / Slunec / app / 16 / MISC.SWG / 0001_TIFF-BMP-LZW ALGORITHMS.pas next >
Pascal/Delphi Source File  |  1996-09-04  |  34KB  |  679 lines

  1. --------!-ALGORITHMS------------------------
  2. Some algorithms used for encoding images etc...
  3. --- TIFF PackBits algorithm
  4.  
  5.           Abstract
  6.  
  7. This  document describes a simple compression scheme for bilevel scanned
  8. and paint type files.
  9.  
  10.  
  11.           Motivation
  12.  
  13. The   TIFF  specification  defines  a  number  of  compression  schemes.
  14. Compression  type  1  is really no  compression,  other than basic pixel
  15. packing. Compression type 2, based on CCITT 1D compression, is powerful,
  16. but  not  trivial  to implement. Compression  type  5  is typically very
  17. effective for most bilevel images, as well as many deeper images such as
  18. palette  color  and  grayscale  images,  but  is  also  not  trivial  to
  19. implement. PackBits is a simple but often effective alternative.
  20.  
  21.  
  22.           Description
  23.  
  24. Several  good  schemes  were  already in  use  in  various  settings. We
  25. somewhat  arbitrarily  picked the Macintosh  PackBits scheme. It is byte
  26. oriented,  so there is no problem with word alignment. And it has a good
  27. worst  case  behavior (at most 1 extra  byte for every 128 input bytes).
  28. For Macintosh users, there are toolbox utilities PackBits and UnPackBits
  29. that  will  do  the work for you, but  it  is easy to implement your own
  30. routines.
  31.  
  32.           A pseudo code fragment to unpack might look like this:
  33.  
  34.        Loop  until  you  get  the  number  of  unpacked  bytes  you  are
  35.        expecting:
  36.              Read the next source byte into n.
  37.              If n is between 0 and 127 inclusive, copy the next n+1 bytes
  38.           literally.
  39.              Else if  n is  between -127  and -1 inclusive, copy the next
  40.           byte -n+1 times.
  41.              Else if n is 128, noop.
  42.           Endloop
  43.  
  44. In  the  inverse routine, it's best to  encode  a 2-byte repeat run as a
  45. replicate  run  except when preceded and  followed  by a literal run, in
  46. which  case  it's best to merge the  three  into one literal run. Always
  47. encode 3-byte repeats as replicate runs.
  48.  
  49.           So that's the algorithm. Here are some other rules:
  50.  
  51.          o    Each row  must be packed separately.  Do not compress across
  52.               row boundaries.
  53.  
  54.          o    The number  of uncompressed  bytes per  row is defined to be
  55.          (ImageWidth +  7) / 8.  If the uncompressed bitmap is required to
  56.          have an  even number  of bytes  per row,  decompress  into  word-
  57.          aligned buffers.
  58.          o    If a  run is  larger  than  128  bytes,  simply  encode  the
  59.          remainder of the run as one or more additional replicate runs.
  60.  
  61. When  PackBits data is uncompressed, the result should be interpreted as
  62. per compression type 1 (no compression).
  63.  
  64. --- TIFF LZW Compression
  65.  
  66.           Abstract
  67.  
  68. This  document  describes  an  adaptive  compression  scheme  for raster
  69. images.
  70.  
  71.           Reference
  72.  
  73. Terry  A.  Welch, "A Technique  for  High Performance Data Compression",
  74. IEEE Computer, vol. 17 no. 6 (June 1984). Describes the basic Lempel-Ziv
  75. & Welch (LZW) algorithm. The author's goal in the article is to describe
  76. a  hardware-based compressor that could be  built into a disk controller
  77. or  database engine, and used on all types of data. There is no specific
  78. discussion of raster images. We intend to give sufficient information in
  79. this Appendix so that the article is not required reading.
  80.  
  81.           Requirements
  82.  
  83. A compression scheme with the following characteristics should work well
  84. in a desktop publishing environment:
  85.  
  86.           o    Must work well for images of any bit depth, including images
  87.           deeper than 8 bits per sample.
  88.           o    Must be effective:  an average compression ratio of at least
  89.           2:1 or  better.    And  it  must  have  a  reasonable  worst-case
  90.           behavior, in case something really strange is thrown at it.
  91.           o    Should  not  depend  on  small  variations  between  pixels.
  92.           Palette color  images tend  to contain  abrupt changes  in  index
  93.           values, due to common patterning and dithering techniques.  These
  94.           abrupt changes  do tend to be repetitive, however, and the scheme
  95.           should make use of this fact.
  96.           o    For images  generated by  paint programs,  the scheme should
  97.           not depend on a particular pattern width.  8x8 pixel patterns are
  98.           common now, but we should not assume that this situation will not
  99.           change.
  100.           o    Must be  fast.   It should  not take  more than 5 seconds to
  101.           decompress a  100K byte  grayscale image on a 68020- or 386-based
  102.           computer.   Compression can  be slower,  but probably not by more
  103.           than a factor of 2 or 3.
  104.           o    The level  of implementation  complexity must be reasonable.
  105.           We would like something that can be implemented in no more than a
  106.           couple of  weeks  by  a competent  software  engineer  with  some
  107.           experience  in   image  processing.     The   compiled  code  for
  108.           compression and  decompression combined  should be  no more  than
  109.           about 10K.
  110.           o    Does not require floating point software or hardware.
  111.  
  112.  
  113.           The following  sections describe  an algorithm based on the "LZW"
  114.           (Lempel-Ziv & Welch) technique that meets the above requirements.
  115.           In addition  meeting our  requirements,  LZW  has  the  following
  116.           characteristics:
  117.  
  118.           o    LZW is fully reversible.  All information is preserved.  But
  119.           if noise  or information  is removed  from an  image, perhaps  by
  120.           smoothing or  zeroing some  low-order bitplanes,  LZW  compresses
  121.           images to  a smaller  size.   Thus,   5-bit, 6-bit, or 7-bit data
  122.           masquerading as  8-bit data  compresses better  than  true  8-bit
  123.           data. Smooth  images also  compress better than noisy images, and
  124.           simple images compress better than complex images.
  125.           o    On a  68082- or  386-based computer,  LZW  software  can  be
  126.           written to  compress at  between 30K  and 80K  bytes per  second,
  127.           depending on image characteristics.  LZW decompression speeds are
  128.           typically about 50K bytes per second.
  129.           o    LZW works  well on  bilevel images,  too.   It always  beats
  130.           PackBits,  and   generally  ties   CCITT  1D  (Modified  Huffman)
  131.           compression, on our test images.  Tying CCITT 1D is impressive in
  132.           that LZW  seems to be considerably faster than CCITT 1D, at least
  133.           in our implementation.
  134.           o    Our implementation is written in C, and compiles to about 2K
  135.           bytes of object code each for the compressor and decompressor.
  136.           o    One of  the nice  things about  LZW is that it is used quite
  137.           widely in  other applications  such as  archival programs, and is
  138.           therefore more of a known quantity.
  139.  
  140.  
  141.           The Algorithm
  142.  
  143. Each  strip  is  compressed independently.  We  strongly  recommend that
  144. RowsPerStrip  be  chosen  such that each  strip  contains about 8K bytes
  145. before  compression. We want to keep the strips small enough so that the
  146. compressed  and uncompressed versions of the  strip can be kept entirely
  147. in  memory  even on small machines,  but large enough to maintain nearly
  148. optimal compression ratios.
  149.  
  150. The LZW algorithm is based on a translation table, or string table, that
  151. maps  strings  of input characters  into  codes. The TIFF implementation
  152. uses  variable-length codes, with a maximum code length of 12 bits. This
  153. string  table  is different for every  strip,  and, remarkably, does not
  154. need  to  be kept around for the  decompressor. The trick is to make the
  155. decompressor  automatically  build  the  same  table  as  is  built when
  156. compressing  the data. We use a C-like pseudocode to describe the coding
  157. scheme:
  158.  
  159.                InitializeStringTable();
  160.                WriteCode(ClearCode);
  161.                Omega = the empty string;
  162.                for each character in the strip {
  163.                     K = GetNextCharacter();
  164.                     if Omega+K is in the string table {
  165.                          Omega = Omega+K;  /* string concatenation */
  166.                     } else {
  167.                          WriteCode (CodeFromString(Omega));
  168.                          AddTableEntry(Omega+K);
  169.                          Omega = K;
  170.                     }
  171.                } /* end of for loop */
  172.                WriteCode (CodeFromString(Omega));
  173.                WriteCode (EndOfInformation);
  174.  
  175. That's  it.  The scheme is simple,  although it is fairly challenging to
  176. implement efficiently. But we need a few explanations before we go on to
  177. decompression.
  178.  
  179. The  "characters" that make up the LZW strings are bytes containing TIFF
  180. uncompressed  (Compression=1)  image  data,  in  our implementation. For
  181. example,  if  BitsPerSample is 4, each  8-bit LZW character will contain
  182. two  4-bit  pixels. If BitsPerSample is  16, each 16-bit pixel will span
  183. two 8-bit LZW characters.
  184.  
  185. (It  is  also  possible  to implement a  version  of  LZW  where the LZW
  186. character  depth  equals BitsPerSample, as was  described  by Draft 2 of
  187. Revision  5.0.  But  there  is a  major  problem  with this approach. If
  188. BitsPerSample  is greater than 11, we  can not use 12-bit-maximum codes,
  189. so  that the resulting LZW table is unacceptably large. Fortunately, due
  190. to  the adaptive nature of LZW, we  do not pay a significant compression
  191. ratio  penalty  for  combining  several  pixels  into  one  byte  before
  192. compressing.  For  example, our 4-bit  sample  images compressed about 3
  193. percent  worse, and our 1-bit images  compressed about 5 percent better.
  194. And  it  is easier to write an  LZW compressor that always uses the same
  195. character  depth  than  it  is to  write  one  which  can handle varying
  196. depths.)
  197.  
  198. We  can now describe some of the  routine and variable references in our
  199. pseudocode:
  200.  
  201. InitializeStringTable()  initializes  the  string  table  to contain all
  202. possible  single-character  strings. There are  256  of them, numbered 0
  203. through 255, since our characters are bytes.
  204.  
  205. WriteCode()  writes a code to the  output stream. The first code written
  206. is a Clear code, which is defined to be code #256.
  207.  
  208.           Omega is our "prefix string."
  209.  
  210. GetNextCharacter()  retrieves  the next character  value  from the input
  211. stream.  This will be number between 0 and 255, since our characters are
  212. bytes.
  213.  
  214.           The "+" signs indicate string concatenation.
  215.  
  216. AddTableEntry() adds a table entry. (InitializeStringTable() has already
  217. put  256 entries in our table. Each entry consists of a single-character
  218. string,  and  its associated code value,  which  is, in our application,
  219. identical  to the character itself. That is,  the 0th entry in our table
  220. consists  of  the string <0>, with  corresponding code value of <0>, the
  221. 1st  entry  in the table consists  of the string <1>, with corresponding
  222. code value of <1>, ..., and the 255th entry in our table consists of the
  223. string  <255>,  with  corresponding code value  of  <255>.) So the first
  224. entry  that  we add to our string  table will be at position 256, right?
  225. Well,  not quite, since we will reserve  code #256 for a special "Clear"
  226. code,  and code #257 for a  special "EndOfInformation" code that we will
  227. write out at the end of the strip. So the first multiple-character entry
  228. added to the string table will be at position 258.
  229.  
  230. Let's try an example. Suppose we have input data that looks like:
  231.  
  232.           Pixel 0:  <7>
  233.           Pixel 1:  <7>
  234.           Pixel 2:  <7>
  235.           Pixel 3:  <8>
  236.           Pixel 4:  <8>
  237.           Pixel 5:  <7>
  238.           Pixel 6:  <7>
  239.           Pixel 7:  <6>
  240.           Pixel 8:  <6>
  241.  
  242. First, we read Pixel 0 into K. OmegaK is then simply <7>, since Omega is
  243. the  empty string at this point. Is the string <7> already in the string
  244. table?  Of  course, since all single  character  strings were put in the
  245. table  by InitializeStringTable(). So set Omega  equal to <7>, and go to
  246. the top of the loop.
  247.  
  248. Read Pixel 1 into K. Does OmegaK (<7><7>) exist in the string table? No,
  249. so  we get to do some real work. We write the code associated with Omega
  250. to output (write <7> to output), and add OmegaK (<7><7>) to the table as
  251. entry  258.  Store K (<7>) into Omega.  Note that although we have added
  252. the  string consisting of Pixel 0 and  Pixel 1 to the table, we "re-use"
  253. Pixel 1 as the beginning of the next string.
  254.  
  255. Back  at  the  top  of the loop. We  read  Pixel  2  into K. Does OmegaK
  256. (<7><7>)  exist in the string table? Yes, the entry we just added, entry
  257. 258, contains exactly <7><7>. So we just add K onto the end of Omega, so
  258. that Omega is now <7><7>.
  259.  
  260. Back  at  the  top  of the loop. We  read  Pixel  3  into K. Does OmegaK
  261. (<7><7><8>)  exist in the string table? No, so write the code associated
  262. with  Omega (<258>) to output, and add OmegaK to the table as entry 259.
  263. Store K (<8>) into Omega.
  264.  
  265. Back  at  the  top  of the loop. We  read  Pixel  4  into K. Does OmegaK
  266. (<8><8>)  exist  in the string table?  No,  so write the code associated
  267. with  Omega  (<8>) to output, and add  OmegaK to the table as entry 260.
  268. Store K (<8>) into Omega.
  269.  
  270.           Continuing, we get the following results:
  271.  
  272.                After reading: We write to output: And add table entry:
  273.                Pixel 0
  274.                Pixel 1   <7>  258: <7><7>
  275.                Pixel 2
  276.                Pixel 3   <258>     259: <7><7><8>
  277.                Pixel 4   <8>  260: <8><8>
  278.                Pixel 5   <8>  261: <8><7>
  279.                Pixel 6
  280.                Pixel 7   <258>     262: <7><7><6>
  281.                Pixel 8   <6>  263: <6><6>
  282.  
  283. WriteCode()  also  requires  some explanation.  The  output code stream,
  284. <7><258><8><8><258><6>... in our example, should be written using as few
  285. bits as possible. When we are just starting out, we can use 9-bit codes,
  286. since  our  new string table entries are  greater than 255 but less than
  287. 512.  But  when we add table entry  512, we must switch to 10-bit codes.
  288. Likewise,  we switch to 11-bit codes at  1024, and 12-bit codes at 2048.
  289. We  will  somewhat arbitrarily limit ourselves  to 12-bit codes, so that
  290. our  table  can  have at most 4096  entries.  If we push it any farther,
  291. tables tend to get too large.
  292.  
  293. What  happens  if we run out of room  in our string table? This is where
  294. the  afore-mentioned Clear code comes in. As  soon as we use entry 4094,
  295. we write out a (12-bit) Clear code. (If we wait any dworder to write the
  296. Clear  code, the decompressor might try to interpret the Clear code as a
  297. 13-bit  code.)  At this point,  the compressor re-initializes the string
  298. table and starts writing out 9-bit codes again.
  299.  
  300. Note  that whenever you write a code and add a table entry, Omega is not
  301. left empty. It contains exactly one character. Be careful not to lose it
  302. when  you write an end-of-table Clear code.  You can either write it out
  303. as  a 12-bit code before writing the  Clear code, in which case you will
  304. want  to  do it right after adding  table entry 4093, or after the clear
  305. code  as  a  9-bit code. Decompression  gives  the same result in either
  306. case.
  307.  
  308. To  make  things a little simpler  for the decompressor, we will require
  309. that   each   strip  begins  with  a   Clear  code,  and  ends  with  an
  310. EndOfInformation code.
  311.  
  312. Every  LZW-compressed  strip must begin on  a byte boundary. It need not
  313. begin on a word boundary. LZW compression codes are stored into bytes in
  314. high-to-low-order  fashion,  i.e.,  FillOrder is  assumed  to  be 1. The
  315. compressed codes are written as bytes, not words, so that the compressed
  316. data will be identical regardless of whether it is an "II" or "MM" file.
  317.  
  318. Note  that the LZW string table is a continuously updated history of the
  319. strings  that  have been encountered in  the  data. It thus reflects the
  320. characteristics of the data, providing a high degree of adaptability.
  321.  
  322.  
  323.           LZW Decoding
  324.  
  325.           The procedure for decompression is a little more complicated, but
  326.           still not too bad:
  327.  
  328.                while ((Code = GetNextCode()) != EoiCode) {
  329.                     if (Code == ClearCode) {
  330.                          InitializeTable();
  331.                          Code = GetNextCode();
  332.                          if (Code == EoiCode)
  333.                               break;
  334.                          WriteString(StringFromCode(Code));
  335.                          OldCode = Code;
  336.                     }  /* end of ClearCode case */
  337.  
  338.                     else {
  339.                          if (IsInTable(Code)) {
  340.                               WriteString(StringFromCode(Code));
  341.                               AddStringToTable(StringFromCode(OldCode)+
  342.                                 FirstChar(StringFromCode(Code)));
  343.                               OldCode = Code;
  344.                          } else {
  345.                               OutString = StringFromCode(OldCode) +
  346.                                   FirstChar(StringFromCode(OldCode));
  347.                               WriteString(OutString);
  348.                               AddStringToTable(OutString);
  349.                               OldCode = Code;
  350.                          }
  351.                     } /* end of not-ClearCode case */
  352.                } /* end of while loop */
  353.  
  354. The  function GetNextCode() retrieves the next  code from the LZW- coded
  355. data. It must keep track of bit boundaries. It knows that the first code
  356. that it gets will be a 9-bit code. We add a table entry each time we get
  357. a  code,  so GetNextCode() must switch over  to  10-bit codes as soon as
  358. string #511 is stored into the table.
  359.  
  360. The   function  StringFromCode()  gets  the  string  associated  with  a
  361. particular code from the string table.
  362.  
  363. The  function AddStringToTable() adds a string  to the string table. The
  364. "+"  sign  joining  the two parts  of  the  argument to AddStringToTable
  365. indicate string concatenation.
  366.  
  367. StringFromCode() looks up the string associated with a given code.
  368.  
  369.           WriteString() adds a string to the output stream.
  370.  
  371.  
  372.           When SamplesPerPixel Is Greater Than 1
  373.  
  374. We  have  so far described the  compression scheme as if SamplesPerPixel
  375. were  always 1, as will be be  the case with palette color and grayscale
  376. images. But what do we do with RGB image data?
  377.  
  378. Tests  on  our sample images indicate  that the LZW compression ratio is
  379. nearly   identical   regardless  of   whether  PlanarConfiguration=1  or
  380. PlanarConfiguration=2,  for  RGB images.  So use whichever configuration
  381. you prefer, and simply compress the bytes in the strip.
  382.  
  383. It  is  worth cautioning that compression  ratios on our test RGB images
  384. were  disappointing  low:  somewhere  between 1.1  to  1  and  1.5 to 1,
  385. depending  on the image. Vendors are urged to do what they can to remove
  386. as  much noise from their images as possible. Preliminary tests indicate
  387. that  significantly  better  compression ratios  are  possible with less
  388. noisy  images.  Even  something  as simple  as  zeroing  out  one or two
  389. least-significant  bitplanes  may be quite  effective, with little or no
  390. perceptible image degradation.
  391.  
  392.  
  393.           Implementation
  394.  
  395. The exact structure of the string table and the method used to determine
  396. if  a  string is already in the  table are probably the most significant
  397. design   decisions  in  the  implementation  of  a  LZW  compressor  and
  398. decompressor.  Hashing has been suggested as  a useful technique for the
  399. compressor. We have chosen a tree based approach, with good results. The
  400. decompressor  is actually more straightforward, as well as faster, since
  401. no search is involved - strings can be accessed directly by code value.
  402.  
  403.  
  404.           Performance
  405.  
  406. Many  people  do  not realize that  the  performance  of any compression
  407. scheme  depends  greatly on the type of  data  to which it is applied. A
  408. scheme that works well on one data set may do poorly on the next.
  409.  
  410. But  since we do not want to  burden the world with too many compression
  411. schemes,  an  adaptive scheme such as LZW  that performs quite well on a
  412. wide  range of images is very desirable. LZW may not always give optimal
  413. compression ratios, but its adaptive nature and relative simplicity seem
  414. to make it a good choice.
  415.  
  416. Experiments  thus far indicate that we  can expect compression ratios of
  417. between  1.5 and 3.0 to 1 from LZW,  with no loss of data, on continuous
  418. tone  grayscale scanned images. If we  zero the least significant one or
  419. two  bitplanes  of  8-bit  data, higher  ratios  can  be achieved. These
  420. bitplanes  often  consist chiefly of noise,  in  which case little or no
  421. loss in image quality will be perceived. Palette color images created in
  422. a  paint  program  generally compress  much  better than continuous tone
  423. scanned images, since paint images tend to be more repetitive. It is not
  424. unusual  to  achieve compression ratios of 10  to 1 or better when using
  425. LZW on palette color paint images.
  426.  
  427. By way of comparison, PackBits, used in TIFF for black and white bilevel
  428. images,  does  not do well on  color  paint images, much less continuous
  429. tone grayscale and color images. 1.2 to 1 seemed to be about average for
  430. 4-bit images, and 8-bit images are worse.
  431.  
  432. It  has  been  suggested  that the CCITT  1D  scheme  could  be used for
  433. continuous  tone  images,  by compressing  each  bitplane separately. No
  434. doubt  some compression could be achieved,  but it seems unlikely that a
  435. scheme  based  on  a fixed table that  is  optimized for word black runs
  436. separated  by  dworder white runs would be  a very good choice on any of
  437. the  bitplanes. It would do quite  well on the high-order bitplanes (but
  438. so  would a simpler scheme like PackBits),  and would do quite poorly on
  439. the  low-order  bitplanes. We believe  that the compression ratios would
  440. generally  not be very impressive, and  the process would in addition be
  441. quite  slow.  Splitting the pixels into  bitplanes and putting them back
  442. together  is somewhat expensive, and the coding is also fairly slow when
  443. implemented in software.
  444.  
  445. Another  approach  that has been suggested  uses  uses a 2D differencing
  446. step  following  by  coding  the  differences  using  a  fixed  table of
  447. variable-length  codes.  This  type of scheme  works  quite well on many
  448. 8-bit  grayscale images, and is probably  simpler to implement than LZW.
  449. But  it  has  a number of disadvantages  when  used on a wide variety of
  450. images.  First,  it  is not adaptive.  This  makes a big difference when
  451. compressing  data such as 8-bit images  that have been "sharpened" using
  452. one  of the standard techniques. Such  images tend to get larger instead
  453. of  smaller  when compressed. Another  disadvantage  of these schemes is
  454. that  they do not do well with a  wide range of bit depths. The built-in
  455. code table has to be optimized for a particular bit depth in order to be
  456. effective.
  457.  
  458. Finally,  we  should  mention  "lossy"  compression  schemes.  Extensive
  459. research   has   been   done   in   the   area   of   lossy,   or   non-
  460. information-preserving  image  compression.  These  techniques generally
  461. yield   much   higher  compression  ratios   than  can  be  achieved  by
  462. fully-reversible,  information-preserving  image  compression techniques
  463. such  as  PackBits  and  LZW.  Some  disadvantages:  many  of  the lossy
  464. techniques  are  so computationally expensive  that hardware assists are
  465. required.  Others  are so complicated  that  most microcomputer software
  466. vendors  could  not afford either the  expense  of implementation or the
  467. increase  in  application object code  size. Yet others sacrifice enough
  468. image quality to make them unsuitable for publishing use.
  469.  
  470. In  spite of these difficulties, we believe that there will one day be a
  471. standardized lossy compression scheme for full color images that will be
  472. usable  for publishing applications  on microcomputers. An International
  473. Standards  Organization group, ISO/IEC/JTC1/SC2/WG8, in cooperation with
  474. CCITT  Study  Group  VIII,  is hard at  work  on  a scheme that might be
  475. appropriate.  We expect that a future  revision of TIFF will incorporate
  476. this  scheme once it is finalized, if  it turns out to satisfy the needs
  477. of  desktop  publishers and others  in the microcomputer community. This
  478. will  augment, not replace, LZW as  an approved TIFF compression scheme.
  479. LZW  will  very  likely remain the  scheme  of  choice for Palette color
  480. images,  and perhaps 4-bit grayscale images, and may well overtake CCITT
  481. 1D and PackBits for bilevel images.
  482.  
  483.  
  484.           Future LZW Extensions
  485.  
  486. Some images compress better using LZW coding if they are first subjected
  487. to  a  process  wherein each pixel  value  is replaced by the difference
  488. between  the pixel and the preceding pixel. Performing this differencing
  489. in  two dimensions helps some images  even more. However, many images do
  490. not compress better with this extra preprocessing, and for a significant
  491. number  of  images,  the  compression ratio  is  actually  worse. We are
  492. therefore  not  making  differencing an integral  part  of  the TIFF LZW
  493. compression scheme.
  494.  
  495. However,  it is possible that a "prediction" stage like differencing may
  496. exist  which is effective over a broad range of images. If such a scheme
  497. is found, it may be incorporated in the next major TIFF revision. If so,
  498. a new value will be defined for the new "Predictor" TIFF tag. Therefore,
  499. all TIFF readers that read LZW files must pay attention to the Predictor
  500. tag.  If  it  is  1, which is  the  default  case, LZW decompression may
  501. proceed  safely.  If it is not 1,  and the reader does not recognize the
  502. specified prediction scheme, the reader should give up.
  503.  
  504.  
  505.           Acknowledgements
  506.  
  507. The  original LZW reference has already been given. The use of ClearCode
  508. as  a  technique  to handle overflow  was  borrowed from the compression
  509. scheme    used   by   the   Graphics   Interchange   Format   (GIF),   a
  510. small-color-paint-image-file  format used by CompuServe  that also is an
  511. adaptation  of the LZW technique. Joff Morgan and Eric Robinson of Aldus
  512. were each instrumental in their own way in getting LZW off the ground.
  513.  
  514.           The TIFF predictor algorithm
  515.  
  516. The  idea  is to make use of  the  fact that many continuous tone images
  517. rarely  vary  much  in pixel value from  one  pixel to the next. In such
  518. images,   if  we  replace  the   pixel  values  by  differences  between
  519. consecutive  pixels, many of the differences  should be 0, plus or minus
  520. 1,  and  so on. This reduces  the apparent information content, and thus
  521. allows LZW to encode the data more compactly.
  522.  
  523. Assuming 8-bit grayscale pixels for the moment, a basic C implementation
  524. might look something like this:
  525.  
  526.                char image[ ][ ];
  527.                int  row, col;
  528.  
  529.                /* take horizontal differences:
  530.                 */
  531.                for (row = 0; row < nrows; row++)
  532.                     for (col = ncols - 1; col >= 1; col--)
  533.                          image[row][col] -= image[row][col-1];
  534.  
  535. If we don't have 8-bit samples, we need to work a little harder, so that
  536. we can make better use of the architecture of most CPUs. Suppose we have
  537. 4-bit  samples, packed two to a byte, in normal TIFF uncompressed (i.e.,
  538. Compression=1)  fashion. In order to find  differences, we want to first
  539. expand  each 4-bit sample into an 8-bit byte, so that we have one sample
  540. per  byte,  low-order  justified. We  then  perform the above horizontal
  541. differencing.  Once the differencing has  been completed, we then repack
  542. the  4-  bit  differences  two to  a  byte,  in normal TIFF uncompressed
  543. fashion.
  544.  
  545. If  the samples are greater than 8 bits deep, expanding the samples into
  546. 16-bit  words instead of 8-bit bytes seems  like the best way to perform
  547. the subtraction on most computers.
  548.  
  549. Note  that we have not lost any data  up to this point, nor will we lose
  550. any  data  later on. It might at  first seem that our differencing might
  551. turn  8-bit  samples into 9-bit differences,  4-  bit samples into 5-bit
  552. differences,  and so on. But it turns  out that we can completely ignore
  553. the "overflow" bits caused by subtracting a larger number from a smaller
  554. number  and  still  reverse  the  process  without  error.  Normal  twos
  555. complement  arithmetic does just what we want. Try an example by hand if
  556. you need more convincing.
  557.  
  558. Up  to  this  point we have  implicitly  assumed that we are compressing
  559. bilevel  or grayscale images. An  additional consideration arises in the
  560. case of color images.
  561.  
  562. If  PlanarConfiguration is 2, there is no problem. Differencing proceeds
  563. the same way as it would for grayscale data.
  564.  
  565. If  PlanarConfiguration is 1, however, things  get a little trickier. If
  566. we didnt do anything special, we would be subtracting red sample values
  567. from  green sample values, green sample  values from blue sample values,
  568. and  blue sample values from red sample values, which would not give the
  569. LZW  coding  stage  much  redundancy to work  with.  So  we  will do our
  570. horizontal  differences with an offset of SamplesPerPixel (3, in the RGB
  571. case).  In other words, we will subtract red from red, green from green,
  572. and   blue  from  blue.  The  LZW  coding  stage  is  identical  to  the
  573. SamplesPerPixel=1  case.  We require that  BitsPerSample be the same for
  574. all 3 samples.
  575.  
  576.  
  577.           Results and guidelines
  578.  
  579. LZW  without  differencing works well  for 1-bit images, 4-bit grayscale
  580. images,  and synthetic color images. But natural 24-bit color images and
  581. some  8-bit  grayscale  images  do  much  better  with differencing. For
  582. example,  our 24-bit natural test images  hardly compressed at all using
  583. "plain"  LZW:  the average compression ratio  was 1.04 to 1. The average
  584. compression  ratio  with  horizontal  differencing  was  1.40  to  1. (A
  585. compression  ratio of 1.40 to 1 means  that if the uncompressed image is
  586. 1.40MB in size, the compressed version is 1MB in size.)
  587.  
  588. Although the combination of LZW coding with horizontal differencing does
  589. not  result in any loss of data, it may be worthwhile in some situations
  590. to  give up some information by removing  as much noise as possible from
  591. the  image  data  before doing  the  differencing, especially with 8-bit
  592. samples.  The simplest way to get rid of noise is to mask off one or two
  593. low-  order  bits of each 8-bit sample.  On  our 24-bit test images, LZW
  594. with horizontal differencing yielded an average compression ratio of 1.4
  595. to  1.  When  the  low-order  bit  was  masked  from  each  sample,  the
  596. compression  ratio climbed to 1.8 to 1; the compression ratio was 2.4 to
  597. 1  when  masking  two  bits, and 3.4  to  1  when masking three bits. Of
  598. course,  the more you mask, the  more you risk losing useful information
  599. adword  with the noise. We encourage you  to experiment to find the best
  600. compromise  for  your device. For some  applications it may be useful to
  601. let the user make the final decision.
  602.  
  603. Interestingly,  most of our RGB  images compressed slightly better using
  604. PlanarConfiguration=1.  One might think that compressing the red, green,
  605. and blue difference planes separately (PlanarConfiguration=2) might give
  606. better  compression results than mixing  the differences together before
  607. compressing  (PlanarConfiguration=1), but this does not appear to be the
  608. case.
  609.  
  610. Incidentally,  we tried taking both horizontal and vertical differences,
  611. but  the extra complexity of two-dimensional differencing did not appear
  612. to  pay  off for most of our test  images. About one third of the images
  613. compressed  slightly better with two-dimensional differencing, about one
  614. third compressed slightly worse, and the rest were about the same.
  615.  
  616. --- BMP RLE_8 compression
  617.  
  618. The BMP can be compressed in two modes, absolute mode and RLE mode. Both
  619. modes can occur anywhere in a single bitmap.
  620.  
  621. The  RLE  mode  is a simple RLE  mechanism,  the first byte contains the
  622. count,  the second byte the pixel to be replicatet. If the count byte is
  623. 0, the second byte is a special, like EOL or delta.
  624.  
  625. In  absolute  mode, the second byte contains  the  number of bytes to be
  626. copied  litteraly. Each absolute run must be word-aligned that means you
  627. will  may have to add an aditional padding byte which is not included in
  628. the count. After an absolute run, RLE compression continues.
  629.  
  630.           Second byte           Meaning
  631.  
  632.                  0              End of line
  633.                  1              End of bitmap
  634.                  2              Delta. The next two bytes are the horizontal
  635.                                 and vertical offsets from the current position
  636.                                 to the next pixel.
  637.              3-255              Switch to absolute mode
  638.  
  639. --- BMP RLE_4 compression
  640.  
  641. RLE_4 compression knows the two modes of the RLE_8 compression, absolute
  642. and RLE. In the RLE mode, the first byte contains the count of pixels to
  643. draw,  the  second byte contains in its  two nibbles the indices off the
  644. pixel colors, the higher 4 bits are the left pixel, the lower 4 bits are
  645. the  right  pixel. Note that two-color  runs are possible to encode with
  646. RLE_4 through this.
  647.  
  648. --- Protracker sample compression / decompression
  649.  
  650. Get the number of sample bytes to process. Call this SamplesLeft.
  651.  
  652.           Set Delta counter to 0.
  653.  
  654.           DO
  655.             Get a byte from the buffer.
  656.             Store the byte in Temp.
  657.             Subtract the Delta counter from the byte.
  658.             Store it in the buffer.
  659.             Move the Temp byte into the Delta Counter
  660.             Decrement SamplesLeft.
  661.           WHILE(SamplesLeft <> 0)
  662.  
  663.           The technique for conversion back to the raw data is:
  664.  
  665.           Get the number of sample bytes to process.
  666.           Call this SamplesLeft.
  667.  
  668.           Set Delta counter to 0.
  669.  
  670.           DO
  671.             Get a byte from the buffer.
  672.             Add onto the byte the Delta Counter.
  673.             Store the byte in Delta Counter.
  674.             Store the byte in Temp.
  675.             Decrement SamplesLeft.
  676.           WHILE(SamplesLeft <> 0)
  677.  
  678.  
  679.